<?php
Class PdoClass{
	static private $ins = null;
	private $_config    = array();
	private $_pdo       = null;
	private $_error     = null;
	private $_stmt      = null;
	
	final public function __construct() {
		$this -> _config  = require CONFIG_PATH . 'Config.php';
		$dsn              = $this -> mysqlDsn($this -> _config['DB']['TYPE'], $this -> _config['DB']['DB'], $this -> _config['DB']['HOST']);
		$user             = $this -> _config['DB']['USER'];
		$pwd              = $this -> _config['DB']['PWD'];

		try {
			$this -> _pdo = new PDO($dsn, $user, $pwd);
			$this -> _pdo ->query("set names utf8");			
		}catch(PDOException $e) {
			echo $e->getMessage();
		}
	}

	private function mysqlDsn($dbType, $dbName, $dbHost) {
		return $dbType . ':dbname=' . $dbName . ';host=' . $dbHost;
	}
	
	static public function getInstance() {
		if(!self::$ins instanceof self) {
			self::$ins = new self();
		}
		return self::$ins;
	}
	
	public function getAll($sql, $data = array()) {
		$data ? $stmt = $this -> execute($sql, $data): $stmt = $this -> execute($sql);
		return $stmt -> fetchAll(PDO::FETCH_ASSOC);
	}
	
	public function getRow($sql, $data = array()) {
		$data ? $stmt = $this -> execute($sql, $data): $stmt = $this -> execute($sql);
		return $stmt -> fetchAll(PDO::FETCH_ASSOC);
	}
	
	public function getOne($sql, $data = array()) {
		$data ? $stmt = $this -> execute($sql, $data): $stmt = $this -> execute($sql);
		return $stmt -> fetch(PDO::FETCH_NUM)[0];
	}
	
	public function execute($sql, $data = array()) {
		$stmt = $this -> prepare($sql);
		$data ? $stmt -> execute($data) : $stmt -> execute();
		LogClass::write($sql, LOG_PATH . $this -> _config['CONFIG']['LOG_FILE']);
		return $stmt;
	}
	
	public function prepare($sql) {
		return $this -> stmt = $this -> _pdo -> prepare($sql);
	}
	
	public function autoExecute($table, $data, $where = '', $action = 'insert') {
		if(!is_array($data)) {
			return false;
		}
		
		$sql = '';
		switch($action) {
			case 'insert':
				$sql .= 'insert into ' . $table . ' (';
				$sql .= implode(',', array_keys($data)) . ')';
				$sql .= " values ('";
				$sql .= implode("','", array_values($data)) . "')";

				$this -> execute($sql);
				return $this -> lastInsertId();
				break;
				
			case 'update':
				$sql .= 'update ' . $table . ' set ';
				foreach($data as $k => $v) {
					$sql .= $k . " = '" . $v . "',";
				}
				$sql = rtrim($sql, ",") . " ";
				$where ? $sql .= $where : $sql .= "limit 1";
				
				$stmt = $this -> execute($sql);
				return $stmt -> rowCount();
				
			default:
				break;
		}
		return false;
	}

	public function lastInsertId() {
		return $this -> _pdo -> lastInsertId();
	}
}
?>